package tr.edu.yildiz.basevaadin.vaadin;

import java.util.Iterator;

import tr.edu.yildiz.dynaView.service.Module;
import tr.edu.yildiz.dynaView.service.ModuleService;
import tr.edu.yildiz.dynaView.service.ModuleServiceListener;

import com.vaadin.Application;
import com.vaadin.ui.Component;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.Window;

public class ModuleDemoApp extends Application implements ModuleServiceListener<Component> {
	
	
	private ModuleService<Component> moduleService;
	
	public ModuleDemoApp(ModuleService moduleService) {
		this.moduleService = moduleService;
	}
	
	private TabSheet tabs;
	
	@Override
	public void init() {
		tabs = new TabSheet();
		tabs.setSizeFull();
		
		for (Module<Component> module : moduleService.getModules()) {
			tabs.addTab(module.createComponent(), module.getName(), null);
		}
		
		setMainWindow(new Window("Module Demo Application", tabs));

		System.out.println("ModuleDemoApp: Application initializing, adding module service listener");
		moduleService.addListener(this);
	}
	
	@Override
	public void close() {
		System.out.println("ModuleDemoApp: Application closing, removing module service listener");
		moduleService.removeListener(this);
		super.close();
	}
	
	public void moduleRegistered(ModuleService<Component> source, Module<Component> module) {
		System.out.println("ModuleDemoApp: Module registered, adding tab");
		tabs.addTab(module.createComponent(), module.getName(), null);
	}
	
	public void moduleUnregistered(ModuleService<Component> source, Module<Component> module) {
		System.out.println("ModuleDemoApp: Module unregistered, removing tab");
		Iterator<Component> it = tabs.getComponentIterator();
		while (it.hasNext()) {
			Component c = it.next();
			if (tabs.getTab(c).getCaption().equals(module.getName())) {
				tabs.removeComponent(c);
				return;
			}
		}
	}

}
